const NodeRSA = require("node-rsa");

const publicKey =
  "-----BEGIN PUBLIC KEY-----\n" +
  "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALeioBkUCbaEqVtbVoBtlYHUUFfrImeN\n" +
  "5v6NyrnVqJ887JgCulu88rvNT8m2SzmSJzmibxLbRx/H8cT2DQdhmisCAwEAAQ==\n" +
  "-----END PUBLIC KEY-----";
const privateKey =
  "-----BEGIN PRIVATE KEY-----\n" +
  "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAt6KgGRQJtoSpW1tW\n" +
  "gG2VgdRQV+siZ43m/o3KudWonzzsmAK6W7zyu81PybZLOZInOaJvEttHH8fxxPYN\n" +
  "B2GaKwIDAQABAkEAmYQ220BJLnCRNHKTSiJSjorz78v+oxuaNMxM4jagFR3rEvRC\n" +
  "XK9iS7eKSCgnVixz6m9KHIJ0JrRK79g1esp5IQIhANrzkvwSnSrFm27eA9oSgZOm\n" +
  "up1ygz1hz/hiePfpXW43AiEA1rU9+9jJqUuU9v7JfUpVjWSAXaxSWmdWXu2V0nj7\n" +
  "Wa0CIC8ObEeapIadw6MXOhKzKYAXNEJEaypVDEJgv4jgccEPAiEAkXkzihQUbrRb\n" +
  "Ng7jjhRzat2Ra+Z51e72QlNPk8+M3fECIHGyirs8oV81wE1RT85NuAGQGhlWqBgb\n" +
  "rD+4hA1WimkU\n" +
  "-----END PRIVATE KEY-----";
/**
 * 生成 RSA 公私钥对
 * @return {Object} { publicKey, privateKey }
 */
const generateRSAKeyPair = () => {
  const key = new NodeRSA({ b: 512 }); // 指定密钥长度

  key.setOptions({ encryptionScheme: "pkcs1" }); // 指定加密格式

  const publicKey = key.exportKey("pkcs8-public-pem"); //制定输出格式
  const privateKey = key.exportKey("pkcs8-private-pem");

  return { publicKey, privateKey };
};

/**
 * 使用公钥进行加密，加密出错会抛出异常
 * @param {any} data 需要加密的数据，会使用 JSON.stringify 序列化
 * @param {string} publicKey
 * @return {string} 加密后的密文
 */
const encrypt = (data, publicKey) => {
  const encrypt = new NodeRSA(publicKey, "pkcs8-public-pem");
  encrypt.setOptions({ encryptionScheme: "pkcs1" });

  return encrypt.encrypt(JSON.stringify(data), "base64");
};

const enPrivatecrypt = (data, privateKey) => {
  const rsa = new NodeRSA({ b: 512 });
  rsa.setOptions({ encryptionScheme: "pkcs1" });
  rsa.importKey(privateKey);
  return rsa.encrypt(JSON.stringify(data), "base64");
};

const dePrivatecrypt = (data, privateKey) => {
  const rsa = new NodeRSA({ b: 512 });
  rsa.setOptions({ encryptionScheme: "pkcs1" });
  rsa.importKey(privateKey);
  return rsa.decrypt(data, "json");
};

/**
 * 对密文进行 RSA 解密。如果解密失败，则抛出异常
 * @param {string} secretText 密文
 * @param {string} privateKey 私钥
 * @return {String} 解密后的明文，会使用 JSON.parse 反序列化
 */
const decrypt = (secretText, privateKey) => {
  const decrypt = new NodeRSA(privateKey, "pkcs8-private-pem");

  // jsencrypt 自身使用的是 pkcs1 加密方案，所以这里设置为 pkcs1
  decrypt.setOptions({ encryptionScheme: "pkcs1" });

  return decrypt.decrypt(secretText, "json");
};

module.exports = {
  publicKey,
  privateKey,
  generateRSAKeyPair,
  encrypt,
  decrypt,
  enPrivatecrypt,
  dePrivatecrypt,
};
